//
//  EFAMsgSelVersionVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/11/1.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAMsgSelVersionVC.h"
#import <MJRefresh.h>
#import <UIScrollView+EmptyDataSet.h>
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "EFAModel.h"
#import "UIColor+XDHex.h"
#import "EFAUtySelCommonVC.h"
#import "EFAMsgSelVersionTCell.h"

@interface EFAMsgSelVersionVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) UIBarButtonItem *saveBarBtnItem;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;
@property (nonatomic, assign) EFAMsgSelVersionVCType viewType;
@property (strong, nonatomic) EFADevVersionModel *versionModel;
@property (strong, nonatomic) EFACompanyCodeModel *companyModel;
@property (strong, nonatomic) EFAUsageCodeModel *usageModel;
@property (readonly, nonatomic) NSArray *dataArray;
@end
static NSString *const kReuseCellId = @"EFAMsgSelVersionTCell";
static NSInteger const kRequestSize = 20;
@implementation EFAMsgSelVersionVC

#pragma mark - life cycle
- (instancetype)initWithViewType:(EFAMsgSelVersionVCType)viewType {
    self = [super init];
    if (self) {
        _viewType = viewType;
    }
    return self;
}
- (instancetype)init {
    NSAssert(NO, @"use initWithViewType");
    return nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    NSArray *array = @[@"选择软件版本", @"选择企业", @"选择用途"];
    
    self.navigationItem.title = array[self.viewType];
//    self.navigationItem.rightBarButtonItem = self.saveBarBtnItem;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)initSubViews {
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
    self.tableView.mj_header = self.mj_header;
    self.tableView.mj_footer = self.mj_footer;
    
        [self.tableView.mj_header beginRefreshing];
//    [self requestDeviceVersionWithHeader:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"没有数据" attributes:dic];
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"global_empty"];
}
//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return 1;
//}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    return self.versionModel.version_list.count;
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EFAMsgSelVersionTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.row < self.dataArray.count) {
        if (self.viewType == EFAMsgSelVersionVCTypeVersion) {
            [cell configViewWithVersionItem:self.versionModel.version_list[indexPath.row]];
        } else if (self.viewType == EFAMsgSelVersionVCTypeCompany) {
            [cell configViewWithCompanyCodeItem:self.companyModel.companycode_list[indexPath.row]];
        } else {
            [cell configViewWithUsageCodeItem:self.usageModel.usagecode_list[indexPath.row]];
        }
    }
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5.9;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row < self.dataArray.count) {
        if (self.successHandle) {
            self.successHandle(self.dataArray[indexPath.row]);
            self.successHandle = nil;
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - event response
- (void)saveBarBtnTapped:(UIBarButtonItem *)item {
    //    if (self.successHandle) {
    //        self.successHandle(self.cfgModel);
    //        self.successHandle = nil;
    //    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - private methods
- (void)jumpToSelectHeartBeat {
    //    EFAUtySelCommonVC *vc = [[EFAUtySelCommonVC alloc] initWithStart:30 end:240 unit:@"S" containsZero:NO];
    //    vc.successHandle = ^(NSInteger selValue) {
    //        self.cfgModel.efairydevicesetting_heartbeat_interval = selValue;
    //        [self refreshWholeView];
    //    };
    //    [self presentViewController:vc animated:YES completion:nil];
}
- (void)jumpToSelectMuteMode {
    //    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"音响模式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //    [alertVC addAction:[UIAlertAction actionWithTitle:@"静音" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    //        self.cfgModel.efairydevicesetting_audio_on = 0;
    //        [self refreshWholeView];
    //    }]];
    //    [alertVC addAction:[UIAlertAction actionWithTitle:@"正常" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    //        self.cfgModel.efairydevicesetting_audio_on = 1;
    //        [self refreshWholeView];
    //    }]];
    //    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    //    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)jumpToSelectPtThv:(EFADevRealTimeDataItem *)item {
    //    if ([[EFADeviceProtocolModel sharedInstance] isSwitchPt:item.pt]) {
    //        NSArray<NSNumber *> *keys = [[EFADeviceProtocolModel sharedInstance] thvRangeArrayWithPt:item.pt];
    //        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:item.cidTitle message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //        for (NSNumber *keyItem in keys) {
    //            NSString *thvValueStr = [[EFADeviceProtocolModel sharedInstance] thvSwitchDescribeWithThv:keyItem.integerValue pt:item.pt];
    //            [alertVC addAction:[UIAlertAction actionWithTitle:thvValueStr style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    //                item.thv = keyItem.integerValue;
    //                [self refreshWholeView];
    //            }]];
    //        }
    //        [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    //        [self presentViewController:alertVC animated:YES completion:nil];
    //    } else {
    //        EFAUtySelCommonVC *vc = [[EFAUtySelCommonVC alloc] initWithStart:item.thvStart end:item.thvEnd unit:item.ptUnit containsZero:YES];
    //        vc.successHandle = ^(NSInteger selValue) {
    //            [item configThv:selValue];
    //            [self refreshWholeView];
    //        };
    //        [self presentViewController:vc animated:YES completion:nil];
    //    }
}
- (void)refreshWholeView {
    // 尾部加载更多的显示
    if (self.versionModel.totalLoad) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.tableView.mj_footer resetNoMoreData];
    }
    self.tableView.mj_footer.hidden = self.versionModel.totalZero;
    
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    if (self.viewType == EFAMsgSelVersionVCTypeVersion) {
        [self requestVersionListWithHeader:isHeader];
    } else if (self.viewType == EFAMsgSelVersionVCTypeCompany) {
        [self requestCompanyCodeListWithHeader:isHeader];
    } else {
        [self requestUsageCodeListWithHeader:isHeader];
    }
}
- (EFADevVersionModel *)versionListWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
    if ([dic[EFAGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.versionModel;
    }
    EFADevVersionModel *temp = [EFADevVersionModel yy_modelWithDictionary:dic[EFAGlobalJsonKeyResult]];
    if (!temp) {
        return self.versionModel;
    }
    if (AddMore && self.versionModel) {
        [self.versionModel addMoreWithData:temp];
    } else {
        self.versionModel = temp;
    }
    return self.versionModel;
}
- (EFACompanyCodeModel *)companyListWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
    if ([dic[EFAGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.companyModel;
    }
    EFACompanyCodeModel *temp = [EFACompanyCodeModel yy_modelWithDictionary:dic[EFAGlobalJsonKeyResult]];
    if (!temp) {
        return self.companyModel;
    }
    if (AddMore && self.companyModel) {
        [self.companyModel addMoreWithData:temp];
    } else {
        self.companyModel = temp;
    }
    return self.companyModel;
}
- (EFAUsageCodeModel *)usageListWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
    if ([dic[EFAGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.usageModel;
    }
    EFAUsageCodeModel *temp = [EFAUsageCodeModel yy_modelWithDictionary:dic[EFAGlobalJsonKeyResult]];
    if (!temp) {
        return self.usageModel;
    }
    if (AddMore && self.usageModel) {
        [self.usageModel addMoreWithData:temp];
    } else {
        self.usageModel = temp;
    }
    return self.usageModel;
}
#pragma mark - network request
- (void)requestVersionListWithHeader:(BOOL)isHeader {
    // 需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    NSInteger last_id = isHeader ? 0 : self.versionModel.version_list.lastObject.efairydeviceversion_id;
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairydevice_id" : @(self.device_id),
                           //                          @"keyword" : @"",
                           @"efairydevicecompanycode_id" : @(self.efairydevicecompanycode_id),
                           @"efairydeviceusagecode_id" : @(self.efairydeviceusagecode_id),
                           @"last_id" : @(last_id),
                           @"size" : @(kRequestSize)};
    NSLog(@"请求版本列表的参数：%@", pars);
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiDeviceVersionList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求版本列表返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        [self versionListWithDictionary:responseObject isAddMore:!isHeader];
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求版本列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}
- (void)requestCompanyCodeListWithHeader:(BOOL)isHeader {
    // 需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    NSInteger last_id = isHeader ? 0 : self.companyModel.companycode_list.lastObject.efairydevicecompanycode_id;
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           //                           @"keyword" : @"",
                           @"last_id" : @(last_id),
                           @"size" : @(kRequestSize)};
    NSLog(@"请求企业编号列表的参数：%@", pars);
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiCompanyCodeList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求企业列表返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        [self companyListWithDictionary:responseObject isAddMore:!isHeader];
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求企业列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}
- (void)requestUsageCodeListWithHeader:(BOOL)isHeader {
    // 需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    NSInteger last_id = isHeader ? 0 : self.usageModel.usagecode_list.lastObject.efairydeviceusagecode_id;
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           //                           @"keyword" : @"",
                           @"last_id" : @(last_id),
                           @"size" : @(kRequestSize)};
    NSLog(@"请求企业编号列表的参数：%@", pars);
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiUsageCodeList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求企业列表返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        [self usageListWithDictionary:responseObject isAddMore:!isHeader];
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求企业列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - getters and setters
- (UIBarButtonItem *)saveBarBtnItem {
    if (!_saveBarBtnItem) {
        _saveBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveBarBtnTapped:)];
        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_saveBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
        NSDictionary * disableBarItemAtt = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen alpha:0.5],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_saveBarBtnItem setTitleTextAttributes:disableBarItemAtt forState:UIControlStateDisabled];
    }
    return _saveBarBtnItem;
}
- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
//        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}
- (NSArray *)dataArray {
    if (self.viewType == EFAMsgSelVersionVCTypeVersion) {
        return self.versionModel.version_list;
    } else if (self.viewType == EFAMsgSelVersionVCTypeCompany) {
        return self.companyModel.companycode_list;
    } else {
        return self.usageModel.usagecode_list;
    }
}
@end
